<?php
declare (strict_types = 1);

namespace app\controller;

use app\common\model\Ad;
use app\common\model\ArticleCate;
use app\common\model\ArticleOrder;
use app\common\model\ArticlePv;
use app\common\model\Content;
use app\common\model\Like;
use app\common\model\Unlike;
use app\common\model\User;
use app\common\model\Video;
use Phpanalysis\Phpanalysis;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Session;
use think\facade\View;
use think\Request;


class Article extends Common
{
    public function __construct()
    {
        parent::__construct();

        $ulist = \app\common\model\User::where(1)->limit(25)->select()->toArray();
        foreach ($ulist as $k => $v){
            $ulist[$k]["label"] = $v["nickname"];
            $ulist[$k]["value"] = $v["id"];
        }
        View::assign("ulist",$ulist);
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {


        View::assign("title","文章列表");
        return  view();
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $user = $this->user;
        if(!$user){
            return redirect((string) url('index/index',['redirect' => 'index/user/index']));
        }
        View::assign("title","文章发布");
        return \view();
    }

    //富文本方式发布文章
    public function create_edit()
    {
        $user = $this->user;
        if(!$user){
            return redirect((string) url('index/index',['redirect' => 'index/user/index']));
        }
        View::assign("title","文章发布");
        return \view();
    }

    //ajax 获取分类
    public function get_cate()
    {
        $pid = \think\facade\Request::post("pid");
        $mod = new ArticleCate();
        $list = $mod->where("pid",$pid)->select();
        return json(["code"=>200,"msg"=>"成功","data"=>$list]);
    }

    public function getusers()
    {
        $ulist = \app\common\model\User::where("username","<>","")
            ->where("headimgurl","<>","")
            ->where("password","=",0)
            ->orderRaw("rand() , id DESC")
            ->limit(25)
            ->select()
            ->toArray();
        foreach ($ulist as $k => $v){
            $ulist[$k]["label"] = $v["nickname"];
            $ulist[$k]["value"] = $v["id"];
        }
        return json(["code"=>200,"data"=>$ulist]);
    }


    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
       
        $user = $this->user;

        if(!$user){
            return redirect((string) url('index/index',['redirect' => 'index/user/index']));
        }
        $d = $request->post();
        $mod = new \app\common\model\Content();
        if(!isset($d["status"])){
            $d["status"] = 1;
        }
        //超级管理员选择了发布文章的用户
        if (isset($d["post_uid"]) && $d["post_uid"] != ''){

            $user = User::find($d["post_uid"]);
        }
        $d["uid"] = $user["id"];
        $d["author"] = $user["nickname"];
        $d["userinfo"] = json_encode($user);

        if(strlen($d["info"]) < 10){
            return  json(["code"=>4000,"msg"=>"文章内容过短"]);
        }
        if(!isset($d["model_id"])){
            $d["model_id"] = 1;
        }


        //修改
        if(isset($d["id"])){
            $mod = Content::find($d["id"]);
        }

        if(!isset($d["cate_id"])){
            $d["cate_id"] = 0;
        }


        foreach ($d as $k => $v){
            if($v == null || !$v || $v=='null'){
                unset($d[$k]);
            }
        }

        $str = $d["info"];
        $temp = $d["info"];
        $str = str_replace("*","",$str);
           $str = str_replace("`","",$str);
           $str = str_replace("\n","",$str);
           $str = str_replace("~","",$str);
           $str = str_replace(">","",$str);
           $str = str_replace("#","",$str);
           $str = str_replace("-","",$str);
           $str = str_replace("|","",$str);
           $str = str_replace("]","",$str);
           $str = str_replace("[","",$str);
        if(!isset($d["intro"])){
            $d["intro"] = mb_substr($str,0,500);
        }

        $d["info"] = $str;

        if(isset($d["table-align"])){
            unset($d["table-align"]);
        }

        $res = $mod->save($d);

        //如果是文章模型，则需要将文章存进去
        if($d["model_id"] == 1){
            $d["info"] = $temp;
            $d["contentid"] = $mod->id;
            if(isset($d["id"])){
                \app\common\model\Article::where("contentid",$d["contentid"])
                ->save($d);
            }else{
                \app\common\model\Article::create($d);
            }

        }
        //其他模型后续补充

        //其他模型后续补充
        if($res){
            //判断百度seo自动提交是否开启，开启则提交
            if(config("baiduzhanzhang.autopushststus") == 1){
                if(config("baiduzhanzhang.url")){
                    $url = [request()->domain().url('Article/read',["id"=>$mod->id])];
                    $push_res = push_to_baidu($url);
                    $push_res = json_decode($push_res,true);
                    if(isset($push_res["success"])){
                        $msg="成功,并且推送成功，今日剩余推送".$push_res["remain"]."条url".$url[0];
                    }else{
                        $msg="成功,推送接口错误，请手动推送";
                    }
                }else{
                    $msg="成功,未设置自动推送URL，不自动推送";
                }
            }else{
                $msg="成功,未开启自动推送";
            }

            return  json(["code"=>200,"msg"=>$msg]);
        }else{
            return  json(["code"=>4000,"msg"=>"请稍后再试"]);
        }
    }

    public function saveInfo()
    {
        return view();
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {

        $article = Content::with(["cate","article"])->find($id);

        //替换文章中的图片为配置的cdn前缀
        if(isset($article["article"]["info"])){
            $article["article"]["info"] = str_replace(\request()->domain(),config('web.cdn'),$article["article"]["info"]);
        }

        if($article["userinfo"]){
            $article["userinfo"] = json_decode($article["userinfo"],true);
        }

        //文章浏览记录新增
        $mod = new ArticlePv();
        $data['aid'] = $id;
        $data['add_time'] = date("Y-m-d H:i:s");
        $data['ip'] = \request()->ip();
        $data['cid'] = $id;
        $data['model_id'] = $article["model_id"];


        //更新文章的展现量
        update_hits($id,2);


        //p($data);die;
        //p($id);die;
        if($user = Session::get("index_user")){
            $data["uid"] = $user["id"];
            $data["nickname"] = $user["nickname"];
            $data["headimgurl"] = $user["headimgurl"];
        }else{
            $data["nickname"] = "访客:".time();
            $data["headimgurl"] = '';
            $data["uid"] = '';
        }
        $mod->save($data);




        Db::name("content")->where("id",$id)
            ->inc("hits")
            ->update();//热度更新
        Db::name("content")->where("id",$id)
            ->inc("rel_hits")
            ->update();//真实点击量
        $info = $article["info"];

        //if(strpos($info,'```') === false){
        //    $is_markdown = 0;
        //}else{
        //
        //}
        $is_markdown = 1;

        View::assign("is_markdown",$is_markdown);


        View::assign("article",$article);


        //将标题分词 便于seo优化
        $pa = new Phpanalysis('utf-8', 'utf-8', true);
        //载入词典
        $pa->LoadDict();
        //执行分词
        $pa->SetSource($article["article"]["title"]);
        $pa->differMax = true;
        $pa->unitWord = true;
        $pa->StartAnalysis( true );
        //$keywords = $pa->GetFinallyResult(',', false);

        $keywords = $pa->GetFinallyKeywords (5); // 获取文章中的n个关键字
        View::assign("keywords",$keywords);
        $keywords_array = explode(",",$keywords);
        View::assign("keywords_array",$keywords_array);




        if($user = Session::get("index_user")){
            $uid = $user["id"];

            $order = Db::name('article_order')
                ->where(
                    ['aid'=>$article['id'],'uid'=>$uid,'status'=>2])
                ->find();
            if($order){
                View::assign('order',$order);
            }else{
                View::assign('order',0);
            }

        }else{

            View::assign('order',0);
        }
        View::assign('title',$article['title']);

        // 上一篇文章和下一篇文章
        $pre_article = Db::name("content")->where("id","<",$id)->order("id DESC")->find();
        $next_article = Db::name("content")->where("id",">",$id)->order("id ASC")->find();

        View::assign('pre_article',$pre_article);
        View::assign('next_article',$next_article);

        //调取评论
        $comment = Db::name("comment")->where("contentid",$id)
            ->json(["userinfo"])
            ->paginate(["query"=>request()->param()]);

        View::assign('comment',$comment);

        //相关推荐 cate_id
        if(isset($article["cate_id"])){
            $about =\app\common\model\Content::with("user")->where("cate_id",$article["cate_id"])
                ->where("id","<>",$id)
                ->order("id DESC")
                ->limit(4)
                ->select();
        }else{
            $about = [];
        }


        View::assign("list",$about);
        if($article["model_id"] == 1){
            $template = "read";
        }

        if($article["model_id"] == 2){
            $template = "video";
            $video = Video::where("contentid",$article["id"])->find();
            View::assign("video",$video);

        }

        if($article["model_id"] == 4){
            $template = "pic";
            $pic = \app\common\model\Images::where("contentid",$article["id"])->find();
            View::assign("pic",$pic);
            View::assign("res",$article);
        }
        //微资讯
        if($article["model_id"] == 5){
            $template = "weizixun";
        }


        if(!isset($template)){
            $template = "read";
        }

        //广告读取
        $ad = Ad::where("board_id",11)
            ->where("status",1)
            ->order(rand())
            ->cache(true)
            ->find();
        View::assign("ad",$ad);


        return view($template);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    //文章点赞
    public function like($aid)
    {
        $where["aid"] = $aid;
        $where["cid"] = $aid;
        $user = $this->user;
        if(!$user){
            $token = input("param.token");
            if($token){
                $u = jwt_decode($token);
                $user["id"] = $u->uid;
            }
        }



        if($user){
            $where["uid"] = $user["id"];
        }else{
            $where["ip"] = \request()->ip();
        }

        $res = Like::where($where)
            ->find();
        if($res){
            \app\common\model\Content::where("id",$aid)->dec("like",1)->update();
            $res->delete();
            return json(["code"=>201,"msg"=>"取消"]);
        }else{
            $where["add_time"] = date("Y-m-d H:i:s",time());
            $where["ip"] = \request()->ip();
            Like::create($where);
            \app\common\model\Content::where("id",$aid)->inc("like",1)->update();
            return json(["code"=>200,"msg"=>"成功"]);
        }
    }

    public function unlike($aid)
    {
        $where["aid"] = $aid;
        $where["cid"] = $aid;

        $user = $this->user;
        if(!$user){
            $token = input("param.token");
            if($token){
                $u = jwt_decode($token);
                $user["id"] = $u->uid;
            }
        }

        if($user){
            $where["uid"] = $user["id"];
        }else{
            $where["ip"] = \request()->ip();
        }
        $res = Unlike::where($where)
            ->find();
        if($res){
            \app\common\model\Content::where("id",$aid)->dec("unlike",1)->update();
            $res->delete();
            return json(["code"=>201,"msg"=>"取消"]);
        }else{
            $where["add_time"] = date("Y-m-d H:i:s",time());
            $where["ip"] = \request()->ip();
            Unlike::create($where);
            \app\common\model\Content::where("id",$aid)->inc("unlike",1)->update();
            return json(["code"=>200,"msg"=>"成功"]);
        }
    }

    //用户购买文章的隐藏积分
    public function ajax_buy_items()
    {
        $uid = session('index_user')["id"];
        $d = request()->param();
        $d["uid"] = $uid;
        $d["aid"] = $d["id"];
        if(isset($d["id"])){
            unset($d["id"]);
        }

        //查找当前文章隐藏信息需要的积分
        $article = \app\common\model\Article::where("id",$d["id"])->find();

        //查询用户积分是否满足购买
        $user = User::where("id",$uid)->find();
        if($user->score  < $article["score"]){
            return json(["code"=>400,"msg"=>"积分不足，无法购买"]);
        }


        //如果有则不需要重复购买
        $mod = new ArticleOrder();
        if($mod->where($d)->find()){
            return json(["code"=>400,"msg"=>"您之前购买过，无需重复购买"]);
        }
        $d["add_time"] = time();

        $res = $mod->save($d);
        if($res){
            return json(["code"=>200,"msg"=>"购买成功"]);
        }else{
            return json(["code"=>400,"msg"=>"购买失败"]);
        }
        
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {


    }

    public function cache_clear()
    {
        Cache::clear();
    }


    //后续优化，暂时由前端判断是否显示按钮，不会暴露给其他人
    public function change_content_is_md($type,$contentid)
    {
        $data["id"] = $contentid;
        $data["is_md"] = $type;
        $res = Content::update($data);
        if($res){
            return json(["code"=>200,"msg"=>"成功"]);
        }else{
            return json(["code"=>400,"msg"=>"失败"]);
        }
    }
}
